package converters;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import org.springframework.core.convert.converter.Converter;

public class StringToDateConverter implements Converter<String, Date> {
	
	
	@Override
	public Date convert(String source) {
		SimpleDateFormat sdf = null;
		if (Pattern.matches("\\d{4}-\\d{2}-\\d{2}", source)) {

			sdf = new SimpleDateFormat("yyyy-MM-dd");
			// 2019-02-29
			sdf.setLenient(false);
			try {
				return sdf.parse(source);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				
			}
		}
		if (Pattern.matches("\\d{2}:\\d{2}:\\d{2}", source)) {

			sdf = new SimpleDateFormat("HH:mm:ss");
			// 2019-02-29
			sdf.setLenient(false);
			try {
				return sdf.parse(source);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				
			}
		}
		if (Pattern.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}", source)) {

			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// 2019-02-29
			sdf.setLenient(false);
			try {
				return sdf.parse(source);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				
			}
		}
		return  null ; 

	}

}
